package com.ptswitch.material.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hxzon.util.BitUtil;
import org.springframework.stereotype.Service;

import com.ptswitch.material.dao.impl.BomMaterialDao;
import com.ptswitch.material.model.material.Bom;
import com.ptswitch.material.model.material.BomMaterial;
import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.service.BomMaterialService;
import com.ptswitch.material.service.BomService;
import com.ptswitch.material.service.MaterialService;

@Service
public class BomMaterialServiceImpl implements BomMaterialService {
    @Resource
    private BomMaterialDao bomMaterialDao;
    @Resource
    private BomService bomSer;
    @Resource
    private MaterialService materialSer;

    public List<BomMaterial> findByBomId(String bomId, int init) {
        List<BomMaterial> bomMaterials = bomMaterialDao.findByBomId(bomId);
        initBomMaterial(bomMaterials, init);
        return bomMaterials;
    }

    public List<BomMaterial> findByMaterialCode(String code, int init) {
        List<BomMaterial> bomMaterials = bomMaterialDao.findByMaterialCode(code);
        initBomMaterial(bomMaterials, init);
        return bomMaterials;
    }

    private void initBomMaterial(List<BomMaterial> bomMaterials, int init) {
        if (BitUtil.isSet(init, Init_Bom)) {
            for (BomMaterial bomMaterial : bomMaterials) {
                Bom bom = bomSer.findById(bomMaterial.getBomId());
                bomMaterial.setBom(bom);
            }
        }
        if (BitUtil.isSet(init, Init_Material)) {
            for (BomMaterial bomMaterial : bomMaterials) {
                Material material = materialSer.findByCode(bomMaterial.getCode());
                bomMaterial.setMaterial(material);
            }
        }
    }

    public void deleteAll() {
        bomMaterialDao.deleteAll();
    }

    public void saveAll(List<BomMaterial> bomMaterials) {
        bomMaterialDao.saveAll(bomMaterials);
    }

}
